package com.isoft.service.impl;

import com.isoft.entity.DfmeCfleEntity;
import com.isoft.mapper.DfmeCfleMapper;
import com.isoft.service.DfmeCfleService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeCfleServiceImpl implements DfmeCfleService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeCfleServiceImpl.class);

    @Autowired
    private DfmeCfleMapper dfmeCfleMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        try {
            if (file == null || file.isEmpty()) {
                throw new IllegalArgumentException("File cannot be null or empty");
            }

            String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
            logger.info("Processing BASE-CFIE XML file: {}, size: {} bytes",
                    file.getOriginalFilename(), file.getSize());

            return parseAndSave(xmlContent);
        } catch (Exception e) {
            logger.error("BASE-CFIE file processing failed", e);
            throw new IOException("Failed to process BASE-CFIE file: " + e.getMessage(), e);
        }
    }

    @Override
    public void parseAndSave(DfmeCfleEntity entity) {
        try {
            if (entity == null) {
                throw new IllegalArgumentException("Entity cannot be null");
            }
            processAircraftData(entity);
        } catch (Exception e) {
            logger.error("Failed to process BASE-CFIE entity", e);
            throw new RuntimeException("Failed to process BASE-CFIE entity: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content cannot be null or empty");
            }

            logger.debug("Original BASE-CFIE XML content: {}",
                    xmlContent.length() > 200 ? xmlContent.substring(0, 200) + "..." : xmlContent);

            DfmeCfleEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeCfleEntity.class);
            if (entity == null) {
                throw new IllegalArgumentException("Failed to parse BASE-CFIE XML: result is null");
            }

            validateEntity(entity);

            processAircraftData(entity);

            return "BASE-CFIE data processed successfully. " +
                    "Message ID: " + entity.getMeta().getMsgId() + ", " +
                    "Aircraft ID: " + entity.getAircraftId();
        } catch (Exception e) {
            logger.error("BASE-CFIE XML processing failed", e);
            throw new RuntimeException("Failed to process BASE-CFIE XML: " + e.getMessage(), e);
        }
    }

    private void validateEntity(DfmeCfleEntity entity) {
        if (entity.getMeta() == null) {
            logger.error("Meta data is missing in XML");
            throw new IllegalArgumentException("Meta data is required");
        }

        if (entity.getCrft() == null) {
            logger.error("CRFT data is missing in XML");
            throw new IllegalArgumentException("CRFT data is required");
        }

        if (entity.getCrft().getAircraftCode() == null || entity.getCrft().getAircraftCode().isEmpty()) {
            logger.warn("Aircraft code is missing or empty");
        }
    }

    private void processAircraftData(DfmeCfleEntity entity) {
        try {
            // 插入元数据
            dfmeCfleMapper.insertMeta(entity);
            logger.info("Inserted meta data, generated MSG_ID: {}", entity.getMeta().getMsgId());

            // 插入飞机信息
            int aircraftCount = dfmeCfleMapper.insertAircraft(entity);
            logger.info("Inserted aircraft info, generated AIRCRAFT_ID: {}, affected rows: {}",
                    entity.getAircraftId(), aircraftCount);

            if (aircraftCount <= 0) {
                throw new RuntimeException("Failed to insert aircraft data, affected rows: " + aircraftCount);
            }
        } catch (Exception e) {
            logger.error("Database operation failed", e);
            throw new RuntimeException("Database operation failed: " + e.getMessage(), e);
        }
    }
}